import axios from 'axios'
import { DIFY_CONFIG } from './config.js'

const API_URL = DIFY_CONFIG.API_URL;
const API_KEY = DIFY_CONFIG.API_KEY;

// 全局统一 user，自动生成并持久化
let USER_ID = localStorage.getItem('dify_user_id')
if (!USER_ID) {
  USER_ID = 'user-' + Math.random().toString(36).slice(2, 10)
  localStorage.setItem('dify_user_id', USER_ID)
}

export function askDify({ question, conversationId }) {
  return axios.post(
    `${API_URL}/chat-messages`,
    {
      inputs: {}, // 严格按照官方文档，inputs 为空对象
      query: question,
      response_mode: "streaming", // 使用 streaming 模式
      conversation_id: conversationId,
      user: USER_ID,
      files: [] // 添加空的 files 数组
    },
    {
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
        'Content-Type': 'application/json'
      }
    }
  )
}

export function getConversations() {
  return axios.get(
    `${API_URL}/conversations?user=${USER_ID}&last_id=&limit=20`,
    {
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
        'Content-Type': 'application/json'
      }
    }
  )
}

export function renameConversation(conversationId, name) {
  return axios.post(
    `${API_URL}/conversations/${conversationId}/name`,
    {
      name,
      auto_generate: false,
      user: USER_ID
    },
    {
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
        'Content-Type': 'application/json'
      }
    }
  )
}

export function deleteConversation(conversationId) {
  return axios.delete(
    `${API_URL}/conversations/${conversationId}`,
    {
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
        'Content-Type': 'application/json'
      },
      data: {
        user: USER_ID
      }
    }
  )
}

// 获取会话历史记录
export function getMessages(conversationId) {
  return axios.get(
    `${API_URL}/messages`,
    {
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
        'Content-Type': 'application/json'
      },
      params: {
        user: USER_ID,
        conversation_id: conversationId
      }
    }
  )
}

let sending = false; // 防止并发

async function handleSendMessage(userInput) {
  if (loading.value || sending) return; // 防止重复发送
  sending = true;
  // 1. 追加用户消息
  messages.value.push({
    id: 'user-' + Date.now(),
    query: userInput
  });
  loading.value = true;
  let answer = '无回复内容';
  let conversationId = activeConversationId.value;
  let isNewConversation = !conversationId;
  try {
    const res = await askDify({ question: userInput, conversationId });
    // 新会话，后端返回新的conversation_id
    if (isNewConversation) {
      // 用工具方法提取 conversation_id
      const newId = extractConversationId(res.data) || (res.data && res.data.conversation_id);
      if (newId) {
        conversationId = newId;
        activeConversationId.value = newId;
        await loadConversations();
        // 新会话创建后，拉取完整历史消息
        const msgRes = await getMessages(conversationId);
        messages.value = (msgRes.data && msgRes.data.data) ? msgRes.data.data : [];
      }
    }
    // ...answer处理逻辑不变
    messages.value.push({
      id: 'ai-' + Date.now(),
      answer
    });
  } catch (e) {
    answer = `抱歉，请求失败。错误信息: ${e.response?.data?.message || e.message || '未知错误'}`;
    messages.value.push({
      id: 'ai-' + Date.now(),
      answer,
      status: 'error'
    });
  }
  loading.value = false;
  sending = false;
}

async function handleDelete(item) {
  if (confirm('确定要删除该会话吗？')) {
    await deleteConversation(item.id)
    await loadConversations()
    // 如果删除的是当前会话
    if (activeConversationId.value === item.id) {
      if (conversations.value.length > 0) {
        // 切换到第一个会话并拉取历史消息
        activeConversationId.value = conversations.value[0].id
        const res = await getMessages(activeConversationId.value)
        messages.value = (res.data && res.data.data) ? res.data.data : []
      } else {
        // 没有会话了，清空右侧
        activeConversationId.value = ''
        messages.value = []
      }
    }
  }
} 